import Vue from "vue";
import Router from "vue-router";
import Layout from "@/layout";
import instance from "@/api/request";
import Cookies from "js-cookie";
import { getOther, flattenMenuArray,AllMenuFlag } from "@/utils/routeUtil";
Vue.use(Router);

let routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/view/Login/index.vue"),
  },
];

const router = new Router({
  routes,
});

// 解决重复导航的问题
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    if (err.name !== 'NavigationDuplicated') throw err;
  });
};

router.beforeEach((to, from, next) => {
  console.log(to, 'to---')
  const token = Cookies.get("token");
  let storedRoutes = localStorage.getItem("menuList") || "[]";
  storedRoutes = JSON.parse(storedRoutes);
  
  // 登录页直接放行
  if (to.path === '/login') {
    return next();
  }
  
  // 无token访问非登录页，重定向到登录页
  if (!token) {
    return next('/login');
  }
  
  // 处理路由为 / 的情况
  if (to.path === '/') {
    if (storedRoutes.length > 0) {
      return next(`${storedRoutes[0].url}`);
    } else {
      return next('/login');
    }
  }
  
  // 从登录页来的请求，且带有token，直接放行，不做路由匹配检查
  if (from.path === '/login' && token) {
    console.log('从登录页跳转过来，直接放行');
    return next();
  }
  
  // 路由未加载或路由数量不足时，加载路由
  if (router.getRoutes().length < 3) {
    try {
      const roleId = localStorage.getItem("roleId") || "100";
      const url = `/government-platform-center/menu/queryByRoleId?roleId=${roleId}`;
      return instance.get(url).then((res2) => {
        if (res2.data.code == 0) {
          localStorage.setItem('AllMenuList', JSON.stringify(res2.data.data))

          let routerTableData = [];
          res2.data.data.forEach((ele) => {
            // 过滤出该系统的所有菜单
            if (AllMenuFlag.includes(ele.thisData.url)) {
              routerTableData.push(...ele.childList);
            }
          });
          const deal = getOther(routerTableData);
          const routerData = flattenMenuArray(deal);
          if (routerData.length > 0) {
            router.addRoute({
              path: "/",
              component: Layout,
              redirect: routerData[0].path,
              children: routerData,
            });
          } 
          return next({ ...to, replace: true });
          // 路由加载完成后，尝试重新导航
        } else {
          Cookies.remove('token');
          return next('/login');
        }
      }).catch(error => {
        console.error("获取菜单数据失败:", error);
        Cookies.remove('token');
        return next('/login');
      });
    } catch (error) {
      console.log(error);
      Cookies.remove('token');
      return next('/login');
    }
  } 
  
  // 添加日志以排查问题
  console.log('路由已加载完成，检查路由:', to.path);
  console.log(router.getRoutes(),'router.getRoutes()')
  let matchRoute = (router.getRoutes() || []).find(item => item.path === to.path)
  console.log(matchRoute,'matchRoute')
  // 恢复路由匹配检查，但保留优化
  if (matchRoute) {
    return next();
  } else {
    // 无效路由，清除登录信息并重定向到登录页
    console.log('路由不匹配，重定向到登录页');
    Cookies.remove('token');
    localStorage.removeItem('AllMenuList');
    return next('/login');
  }
});
export default router;
